using System.Collections.Generic;
using KenEgozi.Com.Domain.Aggregates.Post;
using KenEgozi.Com.Domain.Interfaces.Repositories;
using NHibernate.Expression;
using Rhino.Commons;

namespace KenEgozi.Com.Domain.Repositories
{
	public class PostsRepository : ARRepository<Post>, IPostsRepository
	{
		public ICollection<Post> FindRecent(int numberOfPosts)
		{
			return FindAll(0, numberOfPosts, Order.Desc("Lifecycle.CreationDate"));
		}

		public ICollection<Post> FindRecent()
		{
			return FindRecent(20);
		}

		public ICollection<Post> FindInArchive(int year, int month)
		{
			string hql = @"
				from Post p
				where 
					year(p.Lifecycle.CreationDate) = :year and
					month(p.Lifecycle.CreationDate) = :month 
				order by p.Lifecycle.CreationDate desc";

			return UnitOfWork.CurrentSession
				.CreateQuery(hql)
				.SetParameter("year", year)
				.SetParameter("month", month)
				.List<Post>();
		}

		public ICollection<Post> FindByUrlFriendlyTagName(string urlFriendlyTagName)
		{
			string hql = @"
				select p 
				from 
							Post p 
					join	p.Tags t
				where t.UrlFriendlyName like :urlFriendlyTagName
				order by p.Lifecycle.CreationDate desc;";

			return UnitOfWork.CurrentSession
				.CreateQuery(hql)
				.SetParameter("urlFriendlyTagName", urlFriendlyTagName)
				.List<Post>();
		}
	}
}
